<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
               label-width="100px">
        <el-form-item label="代理代码" prop="identityCode">
          <el-input
            v-model="queryParams.identityCode"
            placeholder="请输入代理代码"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input
            v-model="queryParams.userName"
            placeholder="请输入用户名称"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input
            v-model="queryParams.phonenumber"
            placeholder="请输入手机号码"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            size="mini"
            @click="handleAdd('1')"
            v-hasPermi="['system:agentInfo:add']"
          >开户参与分销 {{ distributionData.agentNum }}
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            size="mini"
            @click="handleAdd('0')"
            v-hasPermi="['system:agentInfo:add']"
          >开户不参与分销 {{ distributionData.notAgentNum }}
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="info"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:agentInfo:edit']"
          >修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:agentInfo:remove']"
          >删除
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
      <el-table v-loading="loading" :data="agentList" @selection-change="handleSelectionChange" border stripe>
        <el-table-column type="selection" width="50" align="center"/>
        <el-table-column label="代理代码" align="center" prop="identityCode"/>
        <el-table-column label="法人姓名" align="center" prop="realName"/>
        <el-table-column label="公司名称" align="center" prop="corporateName" width="120"/>
        <el-table-column label="信用代码" align="center" prop="creditCode" width="120"/>
        <el-table-column label="分公司名称" align="center" prop="parentBranchName" width="120">
          <template slot-scope="scope">
            {{ scope.row.parentBranchId ? scope.row.parentBranchName : '暂无' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button size="mini" type="text" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="branchForm" :model="branchForm" :rules="branchRules" label-width="150px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名：" prop="userName">
              <el-input v-model="branchForm.userName" placeholder="请输入用户名称" maxlength="30"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电子邮箱：" prop="email">
              <el-input v-model="branchForm.email" placeholder="请输入电子邮箱" maxlength="50"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码：" prop="phonenumber">
              <el-input v-model="branchForm.phonenumber" placeholder="请输入手机号码" maxlength="11"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="法人姓名：" prop="legalPerson">
              <el-input v-model="branchForm.legalPerson" placeholder="请输入法人姓名" maxlength="11"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="!branchForm.identityCode">
          <el-col :span="12">
            <el-form-item label="所属分公司：" prop="parentBranchId">
              <el-select v-model="branchForm.parentBranchId" filterable v-if="userInfo.userId == 1"
                         placeholder="请选择所属分公司" @change="chooseBranch">
                <el-option
                  v-for="item in companyList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
              <el-input v-else v-model="branchForm.parentBranchId" disabled placeholder="请输入所属分公司"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="直推代理：" prop="parentId">
              <el-select v-model="branchForm.parentId" filterable
                         placeholder="请选择直推代理">
                <el-option
                  v-for="item in pushAgentList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="真实姓名：" prop="realName">
              <el-input v-model="branchForm.realName" placeholder="请输入真实姓名" maxlength="11"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司名称：" prop="corporateName">
              <el-input v-model="branchForm.corporateName" placeholder="请输入公司名称" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" v-if="!branchForm.identityCode">
            <el-form-item label="密码：" prop="password">
              <el-input v-model="branchForm.password" placeholder="请输入密码" autocomplete="new-password"
                        type="password" maxlength="20"
                        show-password/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="信用代码：" prop="creditCode">
              <el-input v-model="branchForm.creditCode" placeholder="请输入信用代码" maxlength="20"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="!branchForm.identityCode">
          <el-col :span="12">
            <el-form-item label="确认密码：" prop="surePassword">
              <el-input v-model="branchForm.surePassword" placeholder="请输入确认密码"
                        type="password" maxlength="20" autocomplete="new-password"
                        show-password/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="营业执照：" prop="businessLicense">
              <image-upload v-model="branchForm.businessLicense" :changeSize="true" :is-show-tip="false" width="50px"
                            height="50px" :limit="2"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证正反面：" prop="agentIdCard">
              <image-upload v-model="branchForm.agentIdCard" :changeSize="true" :is-show-tip="false" width="50px"
                            height="50px" :limit="2"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="上传证书：" prop="certificate">
              <image-upload v-model="branchForm.certificate" :changeSize="true" :is-show-tip="false" width="50px"
                            height="50px" :limit="2"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上传合同：" prop="contract">
              <image-upload v-model="branchForm.contract" :changeSize="true" :is-show-tip="false" width="50px"
                            height="50px" :limit="2"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="法人身份证正反面：" prop="legalIdCard">
              <image-upload v-model="branchForm.legalIdCard" :changeSize="true" :is-show-tip="false" width="50px"
                            height="50px" :limit="2"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addInfo, queryList, queryInfo, editInfo, deleteInfo, queryAgentByBranchId, queryCompanyList
} from "@/api/organize/agent";
import {queryDistributionLimit, queryUserInfoByBranchId} from "@/api/organize/personal";

export default {
  name: "User",
  dicts: ['sys_normal_disable', 'sys_user_sex'],
  data() {
    const equalToPassword = (rule, value, callback) => {
      if (this.branchForm.password !== value) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };
    return {
      loading: true,// 遮罩层
      ids: [], // 选中数组
      single: true, // 非单个禁用
      multiple: true, // 非多个禁用
      showSearch: true, // 显示搜索条件
      total: 0,// 总条数
      companyList: [],//分公司列表
      parentList: [],//上级公司列表
      agentList: [],//代理公司列表
      pushAgentList: [],//直推代理列表
      title: "",// 弹出层标题
      open: false,// 是否显示弹出层
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined
      },
      // 表单校验
      branchRules: {
        userName: [
          {required: true, message: "用户名称不能为空", trigger: "blur"},
          {min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur'}
        ],
        password: [{required: true, message: "用户密码不能为空", trigger: "blur"},
          {min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur'}],
        surePassword: [{required: true, message: "确认密码不能为空", trigger: "blur"},
          {validator: equalToPassword, required: true, trigger: "blur"}],
        email: [{required: true, type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"]}],
        phonenumber: [{
          required: true,
          pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
          message: "请输入正确的手机号码",
          trigger: "blur"
        }],
        realName: [{required: true, message: "真实姓名不能为空", trigger: "blur"}],
        // legalPerson: [{required: true, message: "法人姓名不能为空", trigger: "blur"}],
        corporateName: [{required: true, message: "公司名称不能为空", trigger: "blur"}],
        parentBranchId: [{required: true, message: "请选择所属分公司", trigger: "change"}],
        // branchName: [{required: true, message: "分公司名称不能为空", trigger: "blur"}],
        creditCode: [{required: false, message: "信用代码不能为空", trigger: "blur"}],
        contract: [{message: "合同不能为空", trigger: "change"}],
        certificate: [{message: "证书不能为空", trigger: "change"}],
        // agentIdCard: [{required: true, message: "请上传身份证照片", trigger: "change"}],
        businessLicense: [{required: false, message: "营业执照不能为空", trigger: "change"}],
        parentId: [{required: false, message: "请选择直推代理", trigger: "change"}],
        isDistribution: [{required: true, message: "请选择是否参与分销", trigger: "change"}],
      },
      branchForm: {},// 代理表单信息
      userInfo: "",
      branchInfo: '',
      distributionData: 0,
      isJoinDistribution: 0,//是否参与分销 0-不参与，1-参与

    };
  },
  created() {
    this.userInfo = this.$store.state.user.urserInfo
    this.getList();
    this.getBranchList()
    this.getAgentAndPersonal()
  },
  methods: {
    // 获取分公司下个人和代理可分销额度
    getDistributionNum() {
      queryDistributionLimit().then(res => {
        this.distributionData = res.data
      })
    },
    // 获取分公司下个人和代理列表
    getAgentAndPersonal() {
      queryUserInfoByBranchId().then(res => {
        console.log('查询分公司下代理和个人列表', res)
        // this.companyList = res.branch
        this.pushAgentList = res.agent
        this.parentList = res.user
        if (res.branch) {
          this.branchInfo = res.branch[0]
        }
        console.log(' this.branchInfo ', this.branchInfo, this.branchForm.parentBranchId)
      })
    },
    // 选择分公司
    chooseBranch(e) {
      console.log('eeee', e, this.branchForm.parentBranchId)
      let data = {
        parentBranchId: e
      }
      queryAgentByBranchId(data).then(res => {
        this.pushAgentList = res
      })
    },
    // 查询代理公司列表
    getList() {
      this.loading = true;
      queryList(this.queryParams).then(response => {
          this.agentList = response.rows;
          this.total = response.total;
          this.loading = false;
          this.getDistributionNum()
        }
      );
    },
    // 递归获取级联列表
    // getTreeData(data) {
    //   for (var i = 0; i < data.length; i++) {
    //     console.log('data', data[i].children, i)
    //     if ((data[i].children && data[i].children.length < 1) || data[i].children == null) {
    //       // children若为空数组，则将children设为undefined
    //       data[i].children = undefined;
    //     } else {
    //       // children若不为空数组，则继续 递归调用 本方法
    //       this.getTreeData(data[i].children);
    //     }
    //   }
    //   return data
    // },
    /** 查询分公司列表 */
    getBranchList() {
      queryCompanyList(this.queryParams).then(response => {
          this.companyList = response;
          console.log('companlist', this.companyList)
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.branchForm = {
        corporateName: undefined,//公司名称
        legalPerson: undefined,//法人姓名
        userName: undefined,
        creditCode: undefined,//信用代码
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        identityCode: "",//公司代码
        agentIdCard: "",//身份证正反面
        legalIdCard: "",//法人身份证正反面
        contract: "",//合同
        certificate: undefined,//证书
        realName: "",
        parentBranchId: this.branchInfo ? this.branchInfo.value : undefined,
        // parentBranchId: this.branchInfo ? this.branchInfo.label : undefined,
        isDistribution: this.isJoinDistribution,//是否参与分销
      };
      // this.branchForm = {
      //   corporateName: "翔翔网络科技有限公司",//公司名称
      //   legalPerson: "王晓翔",//法人姓名
      //   userName: 'wxx',
      //   creditCode: '2312312',//信用代码
      //   password: "111111",
      //   phonenumber: '13336782930',
      //   email: "313@qq.com",
      //   identityCode: "",//公司代码
      //   agentIdCard: "",//身份证正反面
      //   legalIdCard: "",//法人身份证正反面
      //   contract: "",//合同
      //   certificate: undefined,//证书
      //   realName: "王晓翔",//真实姓名
      //   isDistribution: this.isJoinDistribution,//是否参与分销
      // };
      this.branchForm.parentBranchId = this.branchInfo.value
      this.resetForm("branchForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd(e) {
      if (e == 1) {
        if (this.distributionData.agentNum == 0) {
          this.$message.error('名额不足！')
          return
        }
      } else {
        if (this.distributionData.notAgentNum == 0) {
          this.$message.error('名额不足！')
          return
        }
      }
      this.isJoinDistribution = e
      this.reset();
      this.open = true;
      this.title = e == 1 ? "参与分销代理开户" : "不参与分销代理开户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      queryInfo(row.id).then(response => {
        this.branchForm = response.data;
        this.open = true;
        this.title = "修改代理信息";
        // this.branchForm.password = "";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["branchForm"].validate(valid => {
        if (valid) {

          // let cardIdList = this.branchForm.agentIdCard.split(';')
          // if (cardIdList && cardIdList.length != 2) {
          //   this.$message.error('身份证照片数量不正确！')
          //   return
          // }
          // if (this.branchInfo) {
          //   this.branchForm.parentBranchId = this.branchInfo.value
          //   // this.branchForm.parentBranchId = this.branchInfo.value
          // }
          console.log('this.branchForm', this.branchForm)
          let data = {
            distributionUser: this.branchForm,
            distributionUserBasicInfo: this.branchForm,
            user: {
              phonenumber: this.branchForm.phonenumber,
              email: this.branchForm.email,
              password: this.branchForm.password,
              surePassword: this.branchForm.surePassword,
              userName: this.branchForm.userName,
            },
            // 需要检查，获取不到
            isDistribution: this.branchForm.isDistribution,
            // 固定模式分销，暂不考虑自定义
            distributionMode: 0
          }
          if (this.branchForm.identityCode) {
            editInfo(data).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInfo(data).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      console.log('this.ids', this.ids)
      const ids = row.id || this.ids.toString();
      this.$modal.confirm('是否确认删除？').then(function () {
        return deleteInfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/user/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    },
  }
};
</script>
